package com.zrc.superframe_net.room.download

import androidx.room.*
import com.google.gson.annotations.SerializedName
import com.zrc.superframe_net.common.download.NetDownloadCallBack
import com.zrc.superframe_net.common.download.NetDownloadObserver
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 * @Author: superman
 * @CreateTime: 6/27/21
 * @Describe:下载请求基础类
 */
@Entity(indices = [Index(value = ["url"], unique = true)])
data class DownloadInfo(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo
    var id: Long = 0,

    @SerializedName("url")
    @ColumnInfo
    var url: String = "",//url

    @SerializedName("savePath")
    @ColumnInfo
    var savePath: String = "",//存储位置

    @SerializedName("readLength")
    @ColumnInfo
    var readLength: Long = 0,//下载长度

    @SerializedName("countLength")
    @ColumnInfo
    var countLength: Long = 0,//文件总长度

    @SerializedName("downState")
    @ColumnInfo
    var downState: Int = 0,//下载状态

    //true为临时缓存DownloadInfo无需存储数据库且文件是没有存入磁盘的（意思就是说该文件只存在于运行内存中）
    //false为需要存储数据库的并且文件文件存储的地址是需要手动删除的
    @Ignore
    var notNeedCache: Boolean = false,

    @Ignore
    var callBack: NetDownloadCallBack? = null, //回调监听: NetDownloadCallBack? = null

    @Ignore
    var observer: NetDownloadObserver<DownloadInfo>? = null //回调监听: NetDownloadCallBack? = null
) {
    //进度条  max:100
    fun getProgress(): Int {
        return (readLength * 1.0 / countLength * 100).toInt()
    }

    //下载状态
    fun getState() = when (downState) {
        0 -> DownloadState.NORMAL
        1 -> DownloadState.WAIT
        2 -> DownloadState.DOWN
        3 -> DownloadState.PAUSE
        4 -> DownloadState.STOP
        5 -> DownloadState.ERROR
        6 -> DownloadState.FINISH
        else -> DownloadState.FINISH
    }

    //对应下载状态，对应因该显示什么文本内容
    fun getStateText() = when (downState) {
        0 -> "下载"
        1 -> "等待"
        2 -> "暂停"
        3 -> "继续"
        4 -> "停止"
        5 -> "重试"
        6 -> "安装"
        else -> "安装"
    }

    companion object {
        private fun bytes2HexString(bytes: ByteArray): String {
            val sb = StringBuilder()
            for (i in bytes.indices) {
                val hex = Integer.toHexString(0xFF and bytes[i].toInt())
                if (hex.length == 1) {
                    sb.append('0')
                }
                sb.append(hex)
            }
            return sb.toString()
        }

         fun getHexString(s: String): String {
            val hashKey: String
            hashKey = try {
                val mDigest = MessageDigest.getInstance("MD5")
                mDigest.update(s.toByteArray())
                bytes2HexString(mDigest.digest())
            } catch (e: NoSuchAlgorithmException) {
                s.hashCode().toString()
            }
            return hashKey
        }
    }
}